package net.xdclass.interceptor;

import io.jsonwebtoken.Claims;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.model.LoginUser;
import net.xdclass.utils.CommonUtils;
import net.xdclass.utils.JWTUtils;
import net.xdclass.utils.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    public static ThreadLocal threadLocal = new ThreadLocal<LoginUser>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("token");
        if (accessToken == null) {
            accessToken = request.getParameter("token");
        }

        if (StringUtils.isNotBlank(accessToken)) {
            Claims claims = JWTUtils.checkJWT(accessToken);
            if (claims == null) {
                CommonUtils.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR));
                return false;
            } else {
                long userId = Long.valueOf(claims.get("id").toString());
                String headImg = claims.get("head_img").toString();
                String mail = claims.get("mail").toString();
                String name = claims.get("name").toString();

                LoginUser loginUser = new LoginUser();
                loginUser.setHeadImg(headImg);
                loginUser.setMail(mail);
                loginUser.setId(userId);
                loginUser.setName(name);


                threadLocal.set(loginUser);

                return true;
            }
        }
        CommonUtils.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR));
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }
}
